package com.wchen.project.zk.demo;

import org.apache.zookeeper.*;

import java.util.concurrent.CountDownLatch;

/**
 * @Desc:   删除节点接口的权限控制案例
 *
 * @author: cww
 * @DateTime: 2020-01-20 16:58
 */

public class ZookeeperAuthDeleteAPI implements Watcher{

    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    final static String PATH = "/zk-book-auth_test";
    final static String PATH2 = "/zk-book-auth_test/child";

    public static void main(String[] args) throws Exception{
        ZooKeeper zooKeeper1 = new ZooKeeper("home:2181", 5000, new ZookeeperAuthDeleteAPI());
        zooKeeper1.addAuthInfo("digest", "foo:true".getBytes());
        zooKeeper1.create(PATH, "init".getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
        zooKeeper1.create(PATH2, "init".getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.EPHEMERAL);

        try {
            ZooKeeper zooKeeper2 = new ZooKeeper("home:2181", 5000, new ZookeeperAuthDeleteAPI());
            zooKeeper2.delete(PATH2, -1);
        } catch (Exception e) {
            System.out.println("删除节点失败：" + e.getMessage());
        }

        ZooKeeper zooKeeper3 = new ZooKeeper("home:2181", 5000, new ZookeeperAuthDeleteAPI());
        zooKeeper3.addAuthInfo("digest", "foo:true".getBytes());
        zooKeeper3.delete(PATH2, -1);
        System.out.println("成功删除节点：" + PATH2);

        ZooKeeper zooKeeper4 = new ZooKeeper("home:2181", 5000, new ZookeeperAuthDeleteAPI());
//        zooKeeper4.addAuthInfo("digest", "foo:true".getBytes());
        zooKeeper4.delete(PATH, -1);
        System.out.println("成功删除节点：" + PATH);
    }

    @Override
    public void process(WatchedEvent event) {
        if (Watcher.Event.KeeperState.SyncConnected == event.getState()) {
            if (Watcher.Event.EventType.None == event.getType() && null == event.getPath()) {
                connectedSemaphore.countDown();
            }
        }
    }

}
